<script setup lang="ts">
import { ref, nextTick, computed, useAttrs } from "vue";
import { components, type IForm } from "./index";
import { t } from "@/lang";
import { debounce } from "lodash-es";

const emit = defineEmits(["change"]);
const props = defineProps({
  is: {
    type: String,
    default: "",
  },
  asyncClose: {
    type: Boolean,
    default: false,
  },
  fullscreen: {
    type: Boolean,
    default: false,
  },
  showCancel: {
    type: Boolean,
    default: true,
  },
  showFooter: {
    type: Boolean,
    default: true,
  },
});
/** 显示/隐藏 */
const visible = ref<boolean>();
const attrs = useAttrs();
const title = ref("");
const formRef = ref<IForm>();

const fullscreen = ref(false);

/**
 * @description 弹框属性
 */
const dialogAttrs = computed(() => {
  return {
    width: "600px",
    showClose: true,
    title: title.value,
    appendToBody: true,
    ...attrs,
  };
});

const currentComponent = computed(() => {
  if (props.is) {
    return components[props.is];
  } else {
    return null;
  }
});

/**
 * @description 显示弹框
 */
function show(t: string, ...args: any[]) {
  visible.value = true;
  title.value = t;
  fullscreen.value = props.fullscreen;
  nextTick(() => {
    formRef.value?.init(...args);
  });
}

function close() {
  visible.value = false;
}

/**
 * @description 关闭弹框
 */
function handleCancel() {
  visible.value = false;
}

/**
 * @description 保存
 */
const handleSave = debounce(() => {
  formRef.value?.submit().then((res: any) => {
    !props.asyncClose && (visible.value = false);
    emit("change", res);
  });
});

defineExpose({
  show,
  close,
});
</script>

<template>
  <el-dialog
    draggable
    class="f-dialog"
    v-model="visible"
    v-bind="dialogAttrs"
    :fullscreen="fullscreen"
    :destroy-on-close="true"
    @closed="fullscreen = false">
    <template #header>
      <div class="dialog-title">{{ title }}</div>
    </template>
    <el-scrollbar height="100%">
      <component
        v-if="currentComponent"
        ref="formRef"
        :is="currentComponent" />
      <span v-else>请设置组件的is属性</span>
    </el-scrollbar>
    <template
      v-if="showFooter"
      #footer>
      <span class="dialog-footer">
        <el-button
          v-if="showCancel"
          @click="handleCancel"
          >{{ t("form.cancel") }}</el-button
        >
        <el-button
          type="primary"
          @click="handleSave"
          >{{ t("form.confirm") }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-opt {
  display: flex;
  position: absolute;
  top: 0;
  right: 0;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
}

.dialog-opt-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 48px;
  cursor: pointer;
}
</style>

<style lang="scss">
.f-form {
  .el-input {
    width: 400px;
  }
}
</style>
